package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi{
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public String publish(Movement movement) {
            // 保存动态详情
        try {
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //movement.setId(ObjectId.get());
            mongoTemplate.save(movement);

            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略实物处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //根据id查询,分页

        Criteria criteria=Criteria.where("userId").is(userId).and("state").is(1);
        Query query=Query.query(criteria);
        //返回结果
        long count = mongoTemplate.count(query, Movement.class);
        query.limit(pagesize)
                .skip((page-1)*pagesize)
                .with( Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize, count,movements);
    }

    /*查询好友动态,分页展示*/
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //1、查询好友时间线表
        Query query = Query.query(Criteria.where("friendId").in(friendId))
                .skip((page - 1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id集合

        List<ObjectId> movementIds = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds).and("state").is(1));
        return mongoTemplate.find(movementQuery, Movement.class);
    }


    /*//随机获取10条动态  Aggregation为聚合查询类：实现对mongo的聚合查询操作*/
    @Override
    public List<Movement> randomRecommend(Integer counts) {
       //1.创建统计对象
        //设置统计参数  Aggregation.sample(counts)：用于指定随机从mongo中查询的条数
        TypedAggregation aggregation = Aggregation
                .newAggregation(Movement.class, Aggregation.sample(counts));
        //2 调用mongoTemplate方法统计
        AggregationResults<Movement> s = mongoTemplate.aggregate(aggregation, Movement.class);
        return s.getMappedResults();
    }
    /*根据PIDs查询*/
    @Override
    public List<Movement> findByPids(List<Long> pids) {
        Query query=Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    /*根据id查询动态*/
    @Override
    public Movement findByMovementId(String movementId) {

        return mongoTemplate.findById(movementId,Movement.class);
    }

    @Override
    public PageResult findByUserId(Long uid, Integer state, Integer page, Integer pagesize) {

//        //根据id查询,分页
//        Criteria criteria=Criteria.where("userId").is(uid).and("state").is(state);
//        Query query=new Query(criteria).limit(pagesize)
//                .skip((page-1)*pagesize)
//                .with( Sort.by(Sort.Order.desc("created")));
//        //返回结果
//        List<Movement> list = mongoTemplate.find(query, Movement.class);
//        long count = mongoTemplate.count(query, Movement.class);
//        return new PageResult(page,pagesize, count,list);
          Query query = new Query().skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }


        @Override
        public void update(String movementId, int state) {
            Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
            Update update = Update.update("state", state);
            mongoTemplate.updateFirst(query,update,Movement.class);
        }
    }



